<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch active-color="#13ce66" inactive-color="#dcdfe6" v-model="scope.row.mg_state" @change="userListChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <el-button type="primary" icon="el-icon-edit" @click="editDialogInfo(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" @click="userRole(scope.row)"></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" @click="removeSuer(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 4, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户信息" :visible.sync="addDialogVisible" width="34%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="ruleForm" label-width="80px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 电话 -->
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!--编辑用户信息对话框  -->
    <el-dialog title="修改用户信息框" :visible.sync="editDialogVisible" width="34%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editRules" ref="editDialogRules" label-width="80px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editModify">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="rolseDialogVisible" width="34%" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户名: {{ userRoleInfo.username }}</p>
        <p>当前的角色: {{ userRoleInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="setRolesId" placeholder="请选择">
            <el-option v-for="item in setRolesListKey" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolseDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 验证邮箱规则
    const addRulesEmail = (rule, value, callback) => {
      //  验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@(([a-zA-Z0-9_-])+\.)+([a-zA-Z0-9]{2,4})+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 手机号验证规则
    const addRulesMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('手机号不对,请重新输入'))
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      // 用户数据集合
      userlist: [],
      // 当前页码
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      rolseDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '用户名长度在 3到 12 个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在 3到 12 个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: addRulesEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: addRulesMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户表单数据
      editForm: {},
      // 编辑表单的验证规则对象
      editRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: addRulesEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: addRulesMobile, trigger: 'blur' }
        ]
      },
      // 当前的用户数据
      userRoleInfo: {},
      // 所有角色的数据列表
      setRolesListKey: [],
      // 已选中的角色id值
      setRolesId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 显示多少条数据
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 分页
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 修改用户状态开关处理函数
    async userListChange(newChange) {
      const { data: res } = await this.$http.put(`users/${newChange.id}/state/${newChange.mg_state}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.ruleForm.resetFields()
    },
    // 点击确定，添加用户
    addUser() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 关闭用户对话框
        this.addDialogVisible = false
        // 重新渲染用户列表数据
        this.getUserList()
      })
    },
    // 编辑，弹出对话框
    async editDialogInfo(id) {
      // 弹出编辑对话框
      this.editDialogVisible = true
      // 根据id查询数据
      const { data: res } = await this.$http.get('users/' + id)
      this.editForm = res.data
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed() {
      this.$refs.editDialogRules.resetFields()
    },
    // 点击修改按钮，更新id用户数据
    editModify() {
      // 发起修改用户信息的数据请求
      this.$refs.editDialogRules.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        // 提示修改成功
        this.$message.success('更新用户信息成功')
        // 关闭对话框
        this.editDialogVisible = false
        // 更新用户列表数据
        this.getUserList()
      })
    },
    // 删除用户
    async removeSuer(id) {
      const configmResult = await this.$confirm('此操作将永久删除用户, 是否继续?', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (configmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 请求删除id用户的数据请求
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      // 更新用户列表数据
      this.getUserList()
    },
    // 点击弹出分配角色对话框
    async userRole(info) {
      this.userRoleInfo = info
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.setRolesListKey = res.data
      this.rolseDialogVisible = true
    },
    // 更新角色
    async saveRoleInfo() {
      if (!this.setRolesId) {
        return this.$message.info('请选择要更新角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userRoleInfo.id}/role`, { rid: this.setRolesId })
      if (res.meta.status !== 200) {
        return this.$message.error('更新用户角色失败')
      }
      this.getUserList()
      this.rolseDialogVisible = false
      this.$message.success('更新角色成功')
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.setRolesId = ''
    }
  }
}
</script>
